package de.godlike.fxbox.persistence.dao;

import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;
import javax.persistence.Query;
import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;

import de.godlike.fxbox.persistence.entity.ServerConfig;

public class ServerConfigDoa {

	private static ServerConfigDoa me;

	private EntityManager em;

	public static ServerConfigDoa getInstance() {
		if (me == null) {
			me = new ServerConfigDoa();
		}
		return me;
	}

	private ServerConfigDoa() {
		EntityManagerFactory emf = Persistence
				.createEntityManagerFactory("fxBox");
		em = emf.createEntityManager();

	}

	public boolean addNewServer(String displayName, String serverUrl,
			String serverUserName, String serverUserPassword) {
		ServerConfig sc = new ServerConfig();
		sc.setDisplayName(displayName);
		sc.setUrl(serverUrl);
		sc.setUsername(serverUserName);
		sc.setPassword(serverUserPassword);
		em.getTransaction().begin();
		em.persist(sc);
		em.getTransaction().commit();
		return true;
	}

	public boolean addNewServer(String displayName, String serverUrl) {
		return this.addNewServer(displayName, serverUrl, "", "");
	}

	public List<ServerConfig> getAllServer() {
		CriteriaBuilder cb = em.getCriteriaBuilder();
		CriteriaQuery<ServerConfig> criteria = cb
				.createQuery(ServerConfig.class);
		Query query = em.createQuery(criteria);
		List<ServerConfig> result = query.getResultList();
		return result;
	}
}
